package ms.core.gateway.tool;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import feign.Feign;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
import feign.Request.Options;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import ms.core.common.ApiResult;
import ms.core.gateway.dto.LWGAuth;

public class FeignTool {

	/**
	 * 接口调用形式采用: url?fn=xxx 格式,如: http://www.abc.com/api?fn=getTime
	 * @param url
	 * @param fn
	 * @param auth
	 * @param body
	 * @return
	 */
	public static ApiResult callFunc(String url, String fn, LWGAuth auth, Object body) {
		FuncCall call = Feign.builder()
					.encoder(new JacksonEncoder())											// 编码格式
					.decoder(new JacksonDecoder())											// 解码格式
					.options(new Options(5, TimeUnit.SECONDS, 10, TimeUnit.SECONDS, true))	// 连接超时和读超时
					.target(FuncCall.class, url);
		return call.execute(fn, auth, body!=null ? body:new HashMap<>());
	}

	/**
	 * 按指定url调用接口,如 http://www.abc.com/api/getTime
	 * 
	 * @param url
	 * @param body
	 * @return
	 */
	public static ApiResult callUrl(String url, LWGAuth auth, Object body) {
		UrlCall call = Feign.builder()
				.encoder(new JacksonEncoder())												// 编码格式
				.decoder(new JacksonDecoder())												// 解码格式
				.options(new Options(5, TimeUnit.SECONDS, 10, TimeUnit.SECONDS, true))		// 连接超时和读超时
				.target(UrlCall.class, url);
		return call.execute(auth, body!=null ? body:new HashMap<>());
	}

	public interface FuncCall {
	    @Headers({"Content-Type: application/json", "Accept: application/json","auth: {auth}"})
	    @RequestLine("POST ?fn={fn}")
	    ApiResult execute(@Param("fn") String fn, @Param("auth") LWGAuth auth, Object body);
	}

	public interface UrlCall {
	    @Headers({"Content-Type: application/json", "Accept: application/json", "auth: {auth}"})
	    @RequestLine("POST")
	    ApiResult execute(@Param("auth") LWGAuth auth, Object body);
	}
}
